package com.eet.rabbitmq.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;

/**
 * 生产者
 *
 * @author zheng.zhang
 */
public class Producer {

    public static void main(String[] args) {
        // 1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("www.eet.ink");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");

        // 2.创建连接
        Connection connection = null;
        Channel channel = null;
        try {
            connection = factory.newConnection();
            // 3.通过连接获取信道
            channel = connection.createChannel();
            // 4.通过通道创建交换器,声明队列,绑定关系,路由Key,发送和接受消息
            String queueName = "test.queue";
            channel.queueDeclare(queueName, true, false, false, null);
            // 5.准备消息内容
            String message = "Hello, I am Li Hua!";
            // 6.发送消息至队列中
            channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());

            System.out.println("消息发送成功!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 7.关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 8.关闭连接
            if (connection != null && connection.isOpen()) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
